package pds.uchiha.corba.manager;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.omg.CORBA.Any;
import org.omg.CORBA.ORB;
import org.omg.CORBA.Object;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.PortableServer.Servant;

public class CorbaManager {
	private ORB orb;
	private POA rootPOA;
	private NamingContextExt nce;
	private static CorbaManager instance = null;
	private CorbaManager() {
		Properties pro = new Properties();
		try{
		pro.load(new FileInputStream(new File("resources/remote.properties")));
		}catch(Exception e){
			System.out.println(e.getMessage());
			pro.put("org.omg.CORBA.ORBInitialHost", "localhost");
			pro.put("org.omg.CORBA.ORBInitialPort", "1500");
		}
		orb = ORB.init(new String[]{}, pro);
		try{
			rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
			rootPOA.the_POAManager().activate();
			
			nce = NamingContextExtHelper.narrow(orb.resolve_initial_references("NameService"));
			
			new Thread(new Runnable() {
				public void run() {
					orb.run();
				}
			}).start();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static CorbaManager getInstance(){
		if(instance == null)
			instance = new CorbaManager();
		return instance;
	}
	public Object publish(Servant obj, String name){
		NameComponent[] ncs = new NameComponent[1];
		ncs[0] = new NameComponent(name, "");
		try{
			Object objRef = rootPOA.servant_to_reference(obj);
			nce.rebind(ncs, objRef);
			return objRef;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	public Object getReference(String name){
		try{
			Object obj = nce.resolve_str(name);
			return obj;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	public Any createAny(){
		return orb.create_any();
	}
	public void shutdown(){
		orb.shutdown(true);
	}
}
